const app = getApp();
const https = require('../../utils/https');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 上传户型图
    certificate: '../../images/upload.png',
    certificates: '',
    // 验房类型
    inspection: [],
    type: ['1', '2'],
    inspection_id: 0,
    name: '',
    price: 0.00,
    surplus_amount: 0, // 优惠后金额
    coupon_count: 0,
    type_name: '请选择验房类型',
    coupon_text: '暂无可使用优惠券',
    order_sn: '',
    //预约时间初始化
    date: '选择预约时间',
    // 小区位置
    baseAreaData: [],
    areaRange:[],
    region: [0,0,0],
    regionActive: '请选择',
  },
  //验房类型选择
  bindtypeChange: function (e) {
    var index = e.detail.value;
    this.setData({
      type_name: this.data.inspection[index].name,
      inspection_id: this.data.inspection[index].id,
      price: this.data.inspection[index].price
    })
  },
  // 时间选择
  bindDateChange: function (e) {
    this.setData({
      date: e.detail.value
    })
  },
  //地址选择
  //地址选择
  bindRegionChange: function (e) {
  
    this.setData({
      regionActive: this.data.areaRange[0][e.detail.value[0]] + this.data.areaRange[1][e.detail.value[1]] + this.data.areaRange[2][e.detail.value[2]],
      city: this.data.areaRange[1][e.detail.value[1]]
    })
  },
  // 地址选择器 列改变
  bindColumnChange: function (e) {
    console.log(e.detail, 'value: ', e.detail.value, 'column: ', e.detail.column)
    const index = e.detail.value;
    const data = {
      region: this.data.region,
      areaRange: this.data.areaRange,
      baseAreaData: this.data.baseAreaData
    };
    data.region[e.detail.column] = index;
    switch (e.detail.column) {
      case 0:
        data.areaRange[1] = data.baseAreaData[index].city.map(c => c.name);
        data.areaRange[2] = data.baseAreaData[index].city[0].zone.map(c => c.name);
        data.region[1] = 0;
        data.region[2] = 0;
        break;
      case 1:
        data.areaRange[2] = data.baseAreaData[data.region[0]].city[index].zone.map(c => c.name);
        data.region[2] = 0;
        break;
    }
    console.log(data);
    this.setData(data);
  },

  getAreaData(){
    https.post('getRegArea', null, false, '正在查询').then(res => {
      this.setData({
        baseAreaData: res,
        areaRange: [res.map(p => p.name), res[0].city.map(c => c.name), res[0].city[0].zone.map( z => z.name)]
      })
    })
  },
  // 上传户型图
  certificateImg: function (e) {
    var that = this
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        that.setData({
          certificate: tempFilePaths,
          certificates: tempFilePaths,
          certificateFirst: true
        });
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options && options.order_sn != '') {
      this.setData({
        order_sn: options.order_sn
      })
      this.getBookOrderInfo();
      this.getInspection();
      this.getAreaData();
    }
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this,
      login_status = wx.getStorageSync('login_status');
    if (!login_status || login_status <= 0) {
      wx.showLoading({
        title: '请先进行登陆',
      })
      setTimeout(() => {
        wx.hideLoading({
          success: (res) => {
            wx.navigateTo({
              url: '/pages/grant/grant',
            })
          },
        })
      }, 1500);
    }
  },
  getBookOrderInfo: function (res) {
    var that = this,
      order_sn = this.data.order_sn;
    https.post('getBookOrderInfo', {
      order_sn: order_sn
    }, true, '正在加载中').then(res => {
      that.setData({
        info: res,
        surplus_amount: res.surplus_amount,
        inspection_id: res.inspection_id,
        date: res.book_time,
        tel: res.tel,
        regionActive: res.position,
        address: res.address,
        house_area: res.house_area,
        area: res.area,
        name: res.name,
        jobActive: res.job_acitve,
        certificate: res.pics
      })
    })
  },
  /**
   * @xk 获取验房类型
   * @param {*} res
   */
  getInspection: function (res) {
    var that = this,
        user_id = wx.getStorageSync('user_id'),
        coupon_text = this.data.coupon_text;
    https.post('getInspection', {user_id: user_id}, false, '正在查询').then(res => {
      if (res.coupon_count > 0) {
        coupon_text = res.coupon_count + '张可用';
      }else{
        coupon_text = '首页领取优惠券';
      }
      that.setData({
        inspection: res.list,
        coupon_text: coupon_text,
        coupon_count: res.coupon_count
      })
    })
  },
  /**
   * @xk 提交预约验房订单
   * @param {} res
   */
  Submit: function (obj) {
    var that = this,
      order_sn = this.data.order_sn,
      book_time = obj.detail.value['date'],
      name = obj.detail.value['name'],
      tel = obj.detail.value['tel'],
      position = this.data.regionActive,
      address = obj.detail.value['address'],
      house_area = obj.detail.value['house_area'],
      area = obj.detail.value['area'],
      newList = this.data.certificates;
    if (book_time == '' || book_time == "选择预约时间") {
      wx.showToast({
        title: '请选择预约时间',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    if (name == '') {
      wx.showToast({
        title: '请填写预约人姓名',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    if (tel == '') {
      wx.showToast({
        title: '请填写预约人电话',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    if (position == '' || position == '小区位置') {
      wx.showToast({
        title: '请选择小区位置',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    if (address == '') {
      wx.showToast({
        title: '请填写详细地址',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    if (house_area == '') {
      wx.showToast({
        title: '请填写楼门牌号等',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    if (area == '' && area <= 0) {
      wx.showToast({
        title: '请填写建筑面积',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    that.setData({
      order_sn: this.data.order_sn,
      book_time: book_time,
      name: name,
      tel: tel,
      position: position,
      address: address,
      house_area: house_area,
      area: area,
    })
    if (newList.length > 0) {
      that.uploadPic({
        path: newList
      });
    } else {
      that.formsubimt();
    }

  },

  formsubimt: function (obj) {
    var that = this,
      order_sn = this.data.order_sn,
      book_time = this.data.book_time,
      name = this.data.name,
      tel = this.data.tel,
      position = this.data.position,
      address = this.data.address,
      house_area = this.data.house_area,
      area = this.data.area,
      pics = this.data.pics;
    https.post('saveUpdateBookOrder', {
      order_sn: order_sn,
      book_time: book_time,
      tel: tel,
      name: name,
      position: position,
      address: address,
      house_area: house_area,
      area: area,
      pics: pics
    }, false, '正在提交修改').then(res => {
      app.globalData.order_sn = res.order_sn;
      if (res.code == 205) {
        //执行微信支付
        wx.requestPayment({
          timeStamp: res.pay_info.timeStamp,
          nonceStr: res.pay_info.nonceStr,
          package: res.pay_info.package,
          signType: res.pay_info.signType,
          paySign: res.pay_info.paySign,
          success(res) {
            if (res.errMsg == 'requestPayment:ok') {
              wx.showToast({
                title: '支付成功',
                icon: 'none',
                duration: 1500
              })
              wx.navigateBack({
                delta: 0,
              })
              // wx.redirectTo({
              //   url: '/pages/booking_order/booking_order',
              // })
            } else {
              wx.showToast({
                title: '支付取消',
                icon: 'none',
                duration: 2000
              })
              wx.navigateBack({
                delta: 0,
              })
            }
          },
          fail(res) {
            wx.showToast({
              title: '支付取消 ',
              icon: 'none',
              duration: 1500
            })
            wx.navigateBack({
              delta: 0,
            })
          }
        })
      } else {
        wx.navigateBack({
          delta: 0,
        })
      }
    })
  },

  uploadPic: function (data) {
    var pics = this.data.pics ? this.data.pics : '';
    var that = this;
    var i = data.i ? data.i : 0; //当前上传的哪张图片
    var success = data.success ? data.success : 0; //上传成功的个数
    var fail = data.fail ? data.fail : 0; //上传失败的个数
    var photo_urls = this.data.photo_urls ? this.data.photo_urls : [];
    wx.uploadFile({
      url: https.url + '/upload',
      filePath: data.path[i],
      name: 'file', //这里根据自己的实际情况改
      formData: {
        id: data.id
      }, //这里是上传图片时一起上传的数据
      success: (resp) => {
        if (resp.data != '') {
          success++; //图片上传成功，图片上传成功的变量+1
          wx.showLoading({
            title: '上传第' + success + '张完成',
          })
          if (pics != '') {
            pics = pics + ',' + resp.data
          } else {
            pics = resp.data
          }
        } else {
          fail++
        }
        that.setData({
          pics: pics,
          imgs: [],
        })
        //这里可能有BUG，失败也会执行这里,所以这里应该是后台返回过来的状态码为成功时，这里的success才+1
      },
      fail: (res) => {
        fail++; //图片上传失败，图片上传失败的变量+1
      },
      complete: () => {
        i++; //这个图片执行完上传后，开始上传下一张
        if (i == data.path.length) { //当图片传完时，停止调用
          wx.hideLoading();
          wx.showToast({
            title: '上传完成',
            icon: 'success',
            duration: 1000
          });
          setTimeout(function () {
            that.formsubimt();
          }, 1000);

        } else { //若图片还没有传完，则继续调用函数
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.uploadPic(data);
        }
      }
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
})
